﻿using System.Data.Linq;
using System.Data.Linq.Mapping;

using Castle.MicroKernel.Facilities;
using Castle.MicroKernel.Registration;

using Wolfbyte.Core;
using Wolfbyte.Core.Repositories;
using Wolfbyte.Core.UnitOfWork;
using System.IO;
using System.Reflection;

namespace Wolfbyte.UnitOfWork.LinqToSql
{
    public class LinqToSqlUnitOfWorkFacility : AbstractFacility
    {
        protected string ConnectionString
        {
            get
            {
                return FacilityConfig.Attributes["ConnectionString"];
            }
        }

        protected string MappingSourceUrl
        {
            get
            {
                return FacilityConfig.Attributes["MappingSourceUrl"];
            }
        }

        protected override void Init()
        {
            var mappingFileUrl = MappingSourceUrl;

            Kernel.Register(
                Component.For(typeof(IRepository<>))
                    .ImplementedBy(typeof(UnitOfWorkApplicationRepository<>)),

                Component.For<IFactory<IUnitOfWork>>()
                    .ImplementedBy<LinqToSqlUnitOfWorkFactory>(),

                Component.For<IFactory<DataContext>>()
                    .ImplementedBy<DataContextFactory>()
                    .Parameters(
                        Parameter.ForKey("FileOrConnectionOrServer").Eq(ConnectionString)
                    ),

                Component.For<IFactory<MappingSource>>()
                    .ImplementedBy<XmlMappingSourceFactory>()
                    .Parameters(
                        Parameter.ForKey("MappingFileName").Eq(mappingFileUrl)
                    )
                );
        }
    }
}
